//
//  RHLocalBleDeviceVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/25.
//

#import "RHLocalBleDeviceVC.h"
#import "RHLocalBleDeviceCell.h"
#import "RHBleDeviceSearchVC.h"
#import "CBLECenterMnger.h"
#import "CBLEDataMnger.h"
#import "RHLocalDeviceVC.h"
#import "CDZQRScanViewController.h"
#import "RHNavigationController.h"
#import "RHSearchView.h"
#import "RHAlertView.h"

@interface RHLocalBleDeviceVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) UIView *BtnView;

@property (nonatomic ,strong) NSArray *localDevArr;

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic ,strong) NSArray *searchDevArr;

@end

@implementation RHLocalBleDeviceVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = @"本地设备".rh_localized;
    
    [self setupUI];
    [self readLocalDevices];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
   
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.recieveMsg = NO;
}


- (void)setupUI{
    ADD_MESSAGE(BLEMSG_LOCAL_DEVICE_CHANGE, msgForLocalDeviceChange);
    ADD_MESSAGE(BLEMSG_PHERAL_CONNECT_RST, msgForPheralConnect);
    self.searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 50)];
    self.searchView.searchTextField.placeholderText = @"请输入设备名称".rh_localized;
    self.searchView.delegate = self;
    [self.view addSubview:self.searchView];
    
    UIBarButtonItem *clearItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"ble_clear_device"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(clearLocalDev)];
    
    self.navigationItem.rightBarButtonItem = clearItem;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHLocalBleDeviceCell class] forCellReuseIdentifier:@"RHLocalBleDeviceCell"];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }

    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    kWeakSelf;
    
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
   
    
    _BtnView = [[UIView alloc] init];
    [_BtnView setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:_BtnView];
    [_BtnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.height.offset(90+kSafe_bottom);
    }];

    QMUIButton *searchBtn = [[QMUIButton alloc]init];
    [searchBtn setTitle:@"蓝牙查找".rh_localized forState:UIControlStateNormal];
    [searchBtn setImage:[UIImage imageNamed:@"ble_search"] forState:UIControlStateNormal];
    [searchBtn setTitleColor:kRGB(63, 68, 67) forState:UIControlStateNormal];
    searchBtn.titleLabel.font = kSYSTEMFONT(14);
    searchBtn.titleLabel.numberOfLines = 2;
    searchBtn.imagePosition = QMUIButtonImagePositionLeft;
    searchBtn.spacingBetweenImageAndTitle = 10;
    searchBtn.backgroundColor = CFTabViewBgColor;
    [searchBtn setCornerRadius:8];
    [_BtnView addSubview:searchBtn];
    
    QMUIButton *scanBtn = [[QMUIButton alloc]init];
    [scanBtn setTitle:@"扫描设备".rh_localized forState:UIControlStateNormal];
    [scanBtn setImage:[UIImage imageNamed:@"ble_scan"] forState:UIControlStateNormal];
    [scanBtn setTitleColor:kRGB(63, 68, 67) forState:UIControlStateNormal];
    scanBtn.titleLabel.font = kSYSTEMFONT(14);
    scanBtn.titleLabel.numberOfLines = 2;
    scanBtn.imagePosition = QMUIButtonImagePositionLeft;
    scanBtn.spacingBetweenImageAndTitle = 10;
    scanBtn.backgroundColor = CFTabViewBgColor;
    [scanBtn setCornerRadius:8];
    [_BtnView addSubview:scanBtn];
    
    [searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake((kUI_WINDOW_W - 55)/2, kScaleW(50)));
        make.left.mas_offset(20);
        make.top.mas_offset(20);
    }];
    
    [scanBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(searchBtn);
        make.right.mas_offset(-20);
        make.top.mas_offset(20);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.left.right.mas_offset(0);
        make.bottom.equalTo(weakSelf.BtnView.mas_top).offset(0);
    }];
    
    [[searchBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        weakSelf.recieveMsg = NO;
        [weakSelf.navigationController pushViewController:[RHBleDeviceSearchVC new] animated:YES];
    }];
    
    [[scanBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf scanQRC];
    }];
}

-(void)readLocalDevices
{
    self.localDevArr = [[CDataPheralMnger dataMnger] readBleDevice];
   
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
   
}

-(void)clearLocalDev
{
    
    QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:@"删除全部设备?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
    QMUIAlertAction *cancel = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:nil];
    QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if ([[CDataPheralMnger dataMnger] deleteAllLocalDevices]) {
            [self readLocalDevices];
        }
        
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:sure];
    [alertVC showWithAnimated:YES];
}


-(void)msgForLocalDeviceChange
{
    [self readLocalDevices];
}

-(void)msgForPheralConnect{
    if (self.recieveMsg == NO) {
        return;
    }
    //取消所有链接超时等待
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [[CBLECenterMnger shareMnger]cmdStopScan];
    //蓝牙设备连接上
    if ([[CBLECenterMnger shareMnger] isConnectOK]){
        [SVProgressHUD dismiss];
        RHLocalDeviceVC *deviceVC = [[RHLocalDeviceVC alloc]init];
        deviceVC.isFromBle = YES;
        deviceVC.title = [CBLECenterMnger shareMnger].curPheral.devName;
        [self.navigationController pushViewController:deviceVC animated:YES];
        
    }else{
        [SVProgressHUD dismiss];
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"connect failed!"];
    }
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.searchDevArr.count>0) {
        return self.searchDevArr.count;
    }
    return self.localDevArr.count;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    RHLocalBleDeviceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHLocalBleDeviceCell"];
    CDataPheralInfo *data = self.localDevArr[indexPath.row];
    if (self.searchDevArr.count>0) {
        data = self.searchDevArr[indexPath.row];
    }
    cell.dataInfo = data;
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    kWeakSelf;
    MGSwipeButton *oneBtn = [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"plant_delete"] backgroundColor:CFTabViewBgColor padding:35 callback:^BOOL(MGSwipeTableCell * _Nonnull cell) {
        QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:NULL];
        QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
            [[CDataPheralMnger dataMnger]deleteLocalDevice:data];
        }];
        QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"删除此设备?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
        [alertController addAction:action1];
        [alertController addAction:action2];
        [alertController showWithAnimated:YES];
        
        return YES;
    }];
    cell.rightButtons = @[oneBtn];
    cell.connectBlock = ^{
        [CBLECenterMnger checkAuthState:^(CBManagerState state) {
            if(state == CBManagerStatePoweredOn){
                weakSelf.recieveMsg = YES;
                [[CBLECenterMnger shareMnger] connectLocalPeripheral:data];
            }
        }];
    };
    return cell;
    
}

#pragma mark ------ 扫描二维码

- (void)scanQRC{
    if ([self isCameraAvailable]) {
        [self isCanVisitPhotoAndCameraAuthorization:^(BOOL isOK,NSString *alerStr) {
            if (isOK) {
                NSLog(@"权限OK");
                kWeakSelf;
                CDZQRScanViewController *controller = [[CDZQRScanViewController alloc] init];
                controller.resultCallBack = ^(NSString *content) {
//                    if ([NSString validateMacAddress:content]) {
                        //通过设备名(设备id)添加
                        CDataPheralInfo *device = [[CDataPheralInfo alloc]init];
                        device.devName = content;
                        [[CBLECenterMnger shareMnger]connectLocalPeripheral:device];
                        weakSelf.recieveMsg = YES;
//                    }else{
//                        [QMUITips showError:@"MAC地址错误".rh_localized];
//                    }
                    
                };
                 RHNavigationController *nav = [[RHNavigationController alloc] initWithRootViewController:controller];
                [nav setModalPresentationStyle:UIModalPresentationOverFullScreen];
                [self presentViewController:nav animated:YES completion:^{
                    
                }];
            }else{
                if (alerStr) {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:alerStr preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"去设置".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                         if (@available(iOS 10.0, *)) {
                             [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
                             } else {
                             NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                             if ([[UIApplication sharedApplication] canOpenURL:url]) {
                                 [[UIApplication sharedApplication] openURL:url];
                             }
                         }
                    }];
                    
                    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消".rh_localized style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        NSLog(@"点击了取消按钮");
                    }];
                    [alert addAction:cancel];
                    [alert addAction:conform];
                    [self presentViewController:alert animated:YES completion:nil];
                }
            }
        }];
    }else{
        NSLog(@"摄像头不可用");
    }

}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.text.length>0) {
        NSMutableArray *mtbArr = [NSMutableArray array];
        [self.localDevArr enumerateObjectsUsingBlock:^(CDataPheralInfo*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj.devName containsString:textField.text]) {
                [mtbArr addObject:obj];
            }
        }];
        self.searchDevArr = mtbArr.copy;
    }else{
        self.searchDevArr = @[];
    }
    
    [self.tableView reloadData];
    return YES;
}

-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    self.searchDevArr = @[];
    [self.tableView reloadData];
    return YES;
}

// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}
- (void)isCanVisitPhotoAndCameraAuthorization:(void(^)(BOOL isOK,NSString *alerStr))result {
    PHAuthorizationStatus photo_status = [PHPhotoLibrary authorizationStatus];
    AVAuthorizationStatus camera_status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (photo_status == PHAuthorizationStatusAuthorized&&camera_status ==AVAuthorizationStatusAuthorized) {
        result(YES,nil);
        return;
    }
    
    if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied||
        camera_status ==AVAuthorizationStatusDenied || camera_status ==AVAuthorizationStatusRestricted) {
        if (photo_status == PHAuthorizationStatusRestricted || photo_status == PHAuthorizationStatusDenied) {
            result(NO,@"Please allow access photos in iPhone's Settings");
        }else{
            result(NO,@"Please allow access camera in iPhone's Settings");
        }
        return ;
    }
    
    if (camera_status == AVAuthorizationStatusNotDetermined) {
        //点击弹框授权
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(!granted){//不允许
                dispatch_async(dispatch_get_main_queue(), ^{
                    NSLog(@"未开启相机权限,请到设置中开启");
                    result(NO,nil);
                });
            }else{
                if (photo_status == PHAuthorizationStatusNotDetermined) {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                               // 回调是在子线程的
                               NSLog(@"%@",[NSThread currentThread]);
                               dispatch_async(dispatch_get_main_queue(), ^{
                                   if (status != PHAuthorizationStatusAuthorized) {
                                         NSLog(@"未开启相册权限,请到设置中开启");
                                         result(NO,nil);
                                   }else{
                                         result(YES,nil);
                                   }
                               });
                     
                           }];
                }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                        result(YES,nil);
                    });
                }

            }
        }];
        return;
    }
    
    if (photo_status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                   // 回调是在子线程的
                   NSLog(@"%@",[NSThread currentThread]);
                   dispatch_async(dispatch_get_main_queue(), ^{
                       if (status != PHAuthorizationStatusAuthorized) {
                             NSLog(@"未开启相册权限,请到设置中开启");
                             result(NO,nil);
                       }else{
                             result(YES,nil);
                       }
                   });
               }];
    }
}

@end
